# 人脸识别
import time

import cv2

cv2.namedWindow("test")
cap = cv2.VideoCapture(0)
success, frame = cap.read()
# 确保此xml文件与该py文件在一个文件夹下，否则将这里改为绝对路径，此xml文件可在D:\My Documents\Downloads\opencv\sources\data\haarcascades下找到。
classifier_face = cv2.CascadeClassifier("haar/haarcascade_frontalface_alt.xml")
classifier_pface = cv2.CascadeClassifier("haar/haarcascade_profileface.xml")
count = 0;

while success:
    time.sleep(0.1)
    success, frame = cap.read()
    size = frame.shape[:2]
    image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.equalizeHist(image, image)
    divisor = 8
    h, w = size
    minSize = (w // divisor, h // divisor)
    afaceRects = classifier_face.detectMultiScale(image, 1.2, 2, cv2.CASCADE_SCALE_IMAGE, minSize)
    pfaceRects = classifier_pface.detectMultiScale(image, 1.2, 2, cv2.CASCADE_SCALE_IMAGE, minSize)
    faceRects = list(afaceRects) + list(pfaceRects)
    if len(faceRects) > 0:
        for faceRect in faceRects:
            x, y, w, h = faceRect
            cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0))
            cv2.imshow("test", frame)
            print("识别成功" + str(count));
            count = count + 1;

    cv2.imshow("test", frame)
    # Abort and exit with 'Q' or ESC
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

cv2.destroyWindow("test")
